 /*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 /**
 * Project  : EasyAvatar-Android
 * Package  : net.solosky.easyavatar.activity
 * File     : MyAvatar.java
 * Author   : solosky < solosky772@qq.com >
 * Created  : Nov 27, 2011
 * License  : Apache License 2.0 
 */
package net.solosky.easyavatar.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.solosky.easyavatar.R;
import net.solosky.easyavatar.bean.Contact;
import net.solosky.easyavatar.utils.Constants;
import net.solosky.easyavatar.utils.Globals;
import net.solosky.easyavatar.utils.Views;
import net.solosky.easyavatar.view.FunctionMenuListAdapter;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

/**
 *
 * 设置我的头像
 *
 * @author solosky <solosky772@qq.com>
 *
 */
public class MyAvatar extends Base implements OnItemClickListener{
	
	private static final int PHOTO_PICKED_WITH_DATA = 3021;
	private static final int CAMERA_WITH_DATA = 3023;
	
	private Contact mMyContact;
	private File mPhotoFile;
	@Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	if(!checkInitilized()){ finish(); return; }
    	
        mMyContact = Globals.CONTACT_MANAGER.getMySelfContact(this);
		
        setContentView(R.layout.ui_myavatar);
        setTitle(R.string.my_avatar);
        setupBackButton();
        updateMyContact();
        
        ListView funcMenuView = (ListView) this.findViewById(R.id.lv_func_menu);
	    funcMenuView.setAdapter(new FunctionMenuListAdapter(this, "myavatar"));
	    funcMenuView.setOnItemClickListener(this);
    }
	
	private void updateMyContact(){
		if(mMyContact!=null){
			TextView tv = (TextView) findViewById(R.id.tv_my_name);
			tv.setText(mMyContact.getName());
			tv = (TextView) findViewById(R.id.tv_my_mobile);
			tv.setText(mMyContact.getMobile());
			ImageView iv = (ImageView) findViewById(R.id.iv_my_avatar);
			if(mMyContact.getHead()!=null){
				iv.setImageBitmap(mMyContact.getHead());
			}else{
				iv.setImageResource(R.drawable.default_avatar);
			}
		}
		
	}
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Intent intent = null;
		switch(position){
			case 0:	//设置我自己的手机号码
				final EditText et = new EditText(this);
				et.setText(mMyContact!=null?mMyContact.getMobile():"");
				 new AlertDialog.Builder(this)
                .setTitle(R.string.set_my_mobile)
                .setView(et)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	String mobile  = et.getText().toString();
                    	Pattern pt = Pattern.compile("^(13[0-9]|15[0|3|6|7|8|9]|18[8|9])\\d{8}$");
                    	Matcher mc = pt.matcher(mobile);
                    	if(mc.matches()){
                    		Editor editor = getSharedPreferences(Constants.DEFAULT_PREFS, 0).edit();
                    		editor.putString("my.mobile", mobile);
                    		editor.commit();
                    		
                    		mMyContact = Globals.CONTACT_MANAGER.getMySelfContact(MyAvatar.this);
                    		updateMyContact();
                    		
                    	}else{
                    		Views.showMessage(Views.S(R.string.info), Views.S(R.string.err_wrong_mobile), null);
                    	}
                    }
                })
                .setNegativeButton(R.string.cancel ,null)
                .create().show();
				break;
				
			case 1: //通过相机照照片设置自己头像
	           mPhotoFile = new File("/sdcard", System.currentTimeMillis()+".jpg");
	           intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
	           intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));
	           startActivityForResult(intent, CAMERA_WITH_DATA);
	           break;
		           
	           
			case 2: //通过选择图库照片来设置头像
				intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		        intent.setType("image/*");
		        intent.putExtra("crop", "true");
		        intent.putExtra("aspectX", 1);
		        intent.putExtra("aspectY", 1);
		        intent.putExtra("outputX", 100);
		        intent.putExtra("outputY", 100);
		        intent.putExtra("return-data", true);
		        startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
			default:;
		}
	}
	
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) return;

        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA:
                final Bitmap photo = data.getParcelableExtra("data");
                mMyContact.setHead(photo);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.PNG, 100, out);
                Globals.CONTACT_MANAGER.setContactPhoto(MyAvatar.this, out.toByteArray(), Long.parseLong(mMyContact.getId()), true);
                break;

            case CAMERA_WITH_DATA: 
            	cropPhoto(mPhotoFile);
                break;
        }
    }
	
	
	private void cropPhoto(File photo){
        MediaScannerConnection.scanFile(
                this,
                new String[] { photo.getAbsolutePath() },
                new String[] { null },
                null);
		Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(Uri.fromFile(photo), "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
	}
}
